/**
 * @Author: wangy
 * @Date: 2022-04-28 10:30:24
 * @Description: 数组学习并测试
 * @Copyright (c) 2022 by wangy, All Rights Reserved.
 */

// 创建和初始化数组
let daysOfWeek1 = new Array();
let daysOfWeek2 = new Array(7);
let daysOfWeek3 = new Array(
	"Sunday",
	"Monday",
	"Tuesday",
	"Wednesday",
	"Thursday",
	"Friday",
	"Staurday"
);
let daysOfWeek4 = [
	"Sunday",
	"Monday",
	"Tuesday",
	"Wednesday",
	"Thursday",
	"Friday",
	"Staurday",
];

// 数组长度和遍历数组
alert("数组长度");
alert("daysOfWeek1:" + daysOfWeek1.length);
alert("daysOfWeek2:" + daysOfWeek2.length);
alert("daysOfWeek3:" + daysOfWeek3.length);
alert("daysOfWeek4:" + daysOfWeek4.length);

// for方法遍历数组
alert("for方法遍历数组");
for (let i = 0; i < daysOfWeek3.length; i++) {
	alert(daysOfWeek3[i]);
}

// 通过forEach遍历数组
alert("forEach遍历数组");
daysOfWeek4.forEach(function (value) {
	alert(value);
});

// 菲波那切数列
alert("菲波那切数列");
let fibonac = [];
fibonac[0] = 1;
fibonac[1] = 1;

for (let i = 2; i < 20; i++) {
	fibonac[i] = fibonac[i - 1] + fibonac[i - 2];
}

alert(fibonac);

// 数组常用操作
let number = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
alert("number:" + number);

// 添加一个元素到数组的最后位置
alert("添加元素");
// 1
number[number.length] = 10;

// 2
number.push(11);
number.push(12, 13);

alert("number:" + number);

// 在元素首位插入一个元素
alert("在元素首位插入一个元素 unshift");
number.unshift(-1);
number.unshift(-4, -3, -2);
alert("number:" + number);

// 删除最后的元素
alert("删除最后的元素 pop");
number.pop();
alert("number:" + number);

// 删除首位元素
alert("删除首位元素 shift");
number.shift();
alert("number:" + number);

// 删除指定位置的几个元素
alert("删除指定位置的几个元素 shift(5,3)");
number.splice(5, 3);
alert("number:" + number);

// 使用spilce插入数据
alert("使用spilce插入数据");
number.splice(5, 3, 3, 2, 1);
alert("number:" + number);

// 数组合并(concat)
alert("数组合并(concat)");
let num1 = [1, 2, 3];
let num2 = [100, 200, 300];
let newNums = num1.concat(num2);
alert("newNum:" + newNums);

// every() : 判断一组元素中是否都包含某个元素
alert("every() : 判断一组元素中是否都包含某个元素");
let names = ["abc", "cb", "mba", "dna"];

let flag = names.every(function (t) {
	alert(t);
	return t.indexOf("a") != -1;
});

alert("flag:" + flag);

// some() : 判断一组元素中是否包含某个元素
alert("some() : 判断一组元素中是否包含某个元素");

let flag1 = names.some(function (t) {
	alert(t);
	return t.indexOf("a") != -1;
});
alert("flag1:" + flag1);

// forEach()方法仅仅是一种快速迭代数组的方式而已
alert("forEach()方法仅仅是一种快速迭代数组的方式而已");
names.forEach(function (t) {
	alert(t);
});

// filter() 方法是一种过滤的函数
alert("filter() 方法是一种过滤的函数");
let newNames = names.filter(function (t) {
	alert(t);
	return t.indexOf("a") != -1;
});
alert("newNames:" + newNames);

// map() 方法：修改数组元素内容
alert("map() 方法：修改数组元素内容");
let newNames1 = names.map(function (t) {
	alert(t);
	return t + "-123";
});
alert("newNames1:" + newNames1);

// 使用reduce方法实现一个数字的累加和
alert("使用reduce方法实现一个数字的累加和");
let numbers = [1, 2, 3, 4];

let total = numbers.reduce(function (pre, cur) {
	alert("pre + cur:" + pre + "+" + cur);
	return pre + cur;
});
alert("total:" + total);
